package com.yyds.blackmagic.service.impl;

import com.yyds.blackmagic.entity.AdminMenu;
import com.yyds.blackmagic.mapper.AdminMenuMapper;
import com.yyds.blackmagic.service.AdminMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * @Author ccc
 * @Date 2021/12/16
 * @Descripton
 */
@Service
@Slf4j
public class AdminMenuServiceImpl implements AdminMenuService {
    @Resource
    AdminMenuMapper adminMenuMapper;

    @Override
    public List<AdminMenu> findByUsername (String username) {
        List<AdminMenu> list = adminMenuMapper.findByUsername(username);
        handleMenus (list);
        return list;
    }

    @Override
    public List<AdminMenu> getMenusByRoleId (Integer id) {
        List<AdminMenu> menus = adminMenuMapper.getMenusByRoleId (id);
        handleMenus(menus);
        return menus;
    }

    @Override
    public int add (int rid, Integer mid) {
        int res = adminMenuMapper.addMenuOfRole(rid,mid);
        return res;
    }

    public void handleMenus(List<AdminMenu> menus) {
        for (AdminMenu menu : menus) {
            List<AdminMenu> children = getAllByParentId(menu.getId());
            menu.setChildren(children);
        }

        Iterator<AdminMenu> iterator = menus.iterator();
        while (iterator.hasNext()) {
            AdminMenu menu = iterator.next();
            if (menu.getParentId () != 0) {
                iterator.remove();
            }
        }
    }

    private List<AdminMenu> getAllByParentId (Integer id) {
        return adminMenuMapper.findAllByParentId(id);
    }

}
